package com.oglvip.business.remote.service.resolvers;

import com.oglvip.business.remote.support.init.ServiceLoader;
import com.oglvip.business.remote.support.proxy.ProxyFactory;
import com.oglvip.business.remote.support.proxy.exchange.Exchanger;
import com.oglvip.business.remote.support.proxy.exchange.RestTemplateExchanger;
import com.oglvip.business.remote.support.utils.ClassUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

/**
 * @auther hanchao
 * @date 2016/12/4 2:29
 */
@Component
public class SpringServiceAdpter implements BeanDefinitionRegistryPostProcessor{
    private static final Logger logger = LoggerFactory.getLogger(SpringServiceAdpter.class);

    private BeanDefinitionRegistry registry;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        this.registry = registry;
    }


    /**
     * 在使用beanfactory时候，由于bean初始化动作在之后，直接请求bean导致了所需要的依赖bean没有完全初始化完成，注意注意
     * @param beanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Exchanger exchanger = new RestTemplateExchanger(beanFactory.getBean(RestTemplate.class));
        Properties properties = new Properties();
        InputStream inputStream = ProxyFactory.class.getClassLoader().getResourceAsStream("hosts.properties");
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ProxyFactory proxyFactory = new ProxyFactory(exchanger,properties);
        ServiceLoader serviceLoader = new ServiceLoader("com.oglvip.business.remote.service.api",proxyFactory);
        serviceLoader.init();

        Map<Class<?>,Object> services = serviceLoader.getServices();

        for (Class<?> clazz : services.keySet()) {
            BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(ServiceFactoryBean.class).addPropertyValue("targetClass",clazz).addPropertyValue("targetBean",services.get(clazz)).getBeanDefinition();
            registry.registerBeanDefinition(ClassUtils.makeBeanName(clazz.getSimpleName())+ServiceFactoryBean.class.getSimpleName(),beanDefinition);
        }
    }

}
